import React from "react";
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { userStore } from "@/store";
import { useAtom } from "jotai";
import { LOGIN_PATH } from "@/config/router.config";

const conf: AxiosRequestConfig = {
  baseURL: '/api',
  timeout: 6000
}

const request: AxiosInstance = axios.create(conf)
let intercrepted = false

function useAjaxEffect(){
  const [,setUser] = useAtom(userStore)

  if(intercrepted){return}
  intercrepted = true // 避免重复注册拦截器

  request.interceptors.request.use((config: AxiosRequestConfig) => {
    const token = window.localStorage.getItem('access-token')
    // 如果token存在，则写入到头部（遵循jwt交互标准）
    token && (config.headers = {Authorization: `Bearer ${token}`})
    return config
  })
  request.interceptors.response.use((response: AxiosResponse) => {
    // 正常请求不做什么处理
    return response
  }, (error) => {
    // 仅拦截401错误（登录页登陆的错误返回也是401，这里需要排除掉）
    if(error.response.status === 401 && (window.location.pathname !== LOGIN_PATH)){
      alert('token过期')
      setTimeout(() =>{
        window.localStorage.removeItem('access-token')
        setUser({})
        window.location.reload()
      }, 300)
    } else {
      // 其他错误由业务代码自行处理
      return Promise.reject(error)
    }
  })
}

function AjaxEffectFragment(){
  useAjaxEffect()
  return <React.Fragment/>
}

export {AjaxEffectFragment};

export default request